package br.perfiman.faces;

import java.util.List;

import javax.faces.model.SelectItem;

import br.perfiman.helpers.GeneralComboHelper;
import br.perfiman.model.Account;
import br.perfiman.model.Person;
import br.perfiman.model.User;
import br.perfiman.service.AbstractService;
import br.perfiman.utils.ServiceLocator;

public class UserBean extends AbstractBean<User> {
	private String passwdConfirm;

	public UserBean() throws Exception {
		if(getEntity() == null) {
			setEntity(new User());
			getEntity().setAccount(new Account());
			getEntity().setPerson(new Person());
		}
		retrieveAll();
	}

	@Override
	@SuppressWarnings("unchecked")
	protected AbstractService<User> getService() throws Exception {
		if(service == null){
			service = (AbstractService<User>) ServiceLocator.getInstance().get("UserServiceBean/remote");
		}
		return service;
	}

	public List<SelectItem> getPersons() throws Exception{
		return GeneralComboHelper.getPersons();
	}

	public String getPasswdConfirm() {
		return passwdConfirm;
	}

	public void setPasswdConfirm(String passwdConfirm) {
		this.passwdConfirm = passwdConfirm;
	}

	@Override
	public String save() throws Exception {
		if(!passwdConfirm.equals(getEntity().getPasswd())){ //wrong password
			return null;
		}
		String accountName = getInternationalizationMessage("userForm_homeAccountName", getEntity().getUsername());
		getEntity().getAccount().setName(accountName);
		return super.save();
	}

	@Override
	public String retrieveById() throws Exception {
		String ret = super.retrieveById();
		setPasswdConfirm(getEntity().getPasswd());
		return ret;
	}
}
